package com.aaa.docter.service.Impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWTUtil;
import com.aaa.docter.Fegin.UserFeign;
import com.aaa.docter.dao.SchedulingDao;
import com.aaa.docter.service.SchedulingService;
import com.aaa.docter.vo.Scheduling2Vo;
import com.aaa.docter.vo.SchedulingDto;
import com.aaa.docter.vo.SchedulingVo;

import com.aaa.entity.Scheduling;
import com.aaa.entity.User;
import com.aaa.util.JwtUtil;
import com.aaa.util.WebUtil;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service

public class SchedulingServiceImpl implements SchedulingService {

    @Autowired
    private UserFeign userFeign;
    @Autowired
    private SchedulingDao schedulingDao;

    @Override
    public Result queryScheduling(@RequestBody SchedulingVo schedulingVo) {


//        1,查询所有医生的信息
        Map<String, Object> map = new HashMap<>();
        map.put("userId", schedulingVo.getUserId());
        map.put("deptId", schedulingVo.getDeptId());
        List<User> users = userFeign.queryUserNeedScheduling(map);
        return querySchedulingByCondition(schedulingVo, users);
    }

//    医生排班，拿到所有医生的排班信息
    @Override
    public Result<List<User>> initUser() {
//        System.out.println("----------------------------=======================");
        List<User> users = userFeign.initUser();
        System.out.println("users = " + users);
        return new Result(2000, "ok", users);
    }

//    我的排版，在token里拿到当前登录用户的信息，并查询出排班信息
    @Override
    public Result<User> getinitUser(SchedulingVo schedulingVo) {
        // 在token里获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        System.out.println("token获取==============12312312====== = " + token);
        Map<String, Object> tokenInfo = JwtUtil.getTokenChaim(token);
        Long phone = Long.valueOf(tokenInfo.get("username").toString());
//        通过token获取登录用户信息
        User byUsername = userFeign.queryUserByPhone(phone);
        System.out.println("通过token获取登录用户信息 = " + byUsername);

        schedulingVo.setUserId(byUsername.getUserId());
        schedulingVo.getBeginDate();
        schedulingVo.getEndDate();
        System.out.println("schedulingVo======================== = " + schedulingVo);
        List<User> list = new ArrayList<>();
        list.add(byUsername);
        return querySchedulingByCondition(schedulingVo, list);
    }

//    修改医生排班信息
    @Override
    public Result updScheduling(Scheduling2Vo scheduling2Vo) {

        // 在token里获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        System.out.println("token获取==============12312312====== = " + token);
        Map<String, Object> tokenInfo = JwtUtil.getTokenChaim(token);
        Long phone = Long.valueOf(tokenInfo.get("username").toString());
//        通过token获取登录用户信息
        User byUsername = userFeign.queryUserByPhone(phone);
        String userName = byUsername.getUserName();

        // System.out.println("通过token获取登录用户信息 = " + byUsername);


        // 获取传输的数据
        List<SchedulingDto> allDatas = scheduling2Vo.getAllDatas();
        String beginDate = scheduling2Vo.getBeginDate();

//        int del = 1;
//        int update = 1;
        DateTime dateTime = DateUtil.parse(beginDate, "yyyy-MM-dd");
        Map<String, String> map = initMap(dateTime);
        Set<String> keys = map.keySet();

        // 遍历
        for (SchedulingDto allData : allDatas) {
            // 删除
            QueryWrapper<Scheduling> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", allData.getUserId());
            wrapper.eq("subsection_type", allData.getSubsectionType());
            wrapper.between("scheduling_day", scheduling2Vo.getBeginDate(), scheduling2Vo.getEndDate());
            schedulingDao.delete(wrapper);

            Collection<String> schedulingType = allData.getSchedulingType();//获取排班
            Iterator<String> scheduling = schedulingType.iterator();//排班 1门诊  2急诊
            Iterator<String> key = keys.iterator();//获取当前的日期
            for (int i = 0; i < keys.size(); i++) {
                String next = scheduling.next();
                String next1 = key.next();
                if (!next.equals("")) {
                    Scheduling user = new Scheduling();
                    user.setUserId(allData.getUserId());
                    user.setDeptId(allData.getDeptId());
                    user.setSubsectionType(allData.getSubsectionType());
                    user.setSchedulingDay(next1);
                    user.setSchedulingType(next);
                    user.setCreateBy(userName);
                    user.setCreateTime(new Date());
                    schedulingDao.insert(user);
                }
            }
        }
        return null;
    }


    //    封装前端需要的数据
    private Result querySchedulingByCondition(SchedulingVo schedulingVo, List<User> users) {
//        获取当前时间
        DateTime date = DateUtil.date();

        if (StringUtils.hasText(schedulingVo.getQueryDate())) {
//            把字符串转化为时间类型
            date = DateUtil.parse(schedulingVo.getQueryDate(), "yyyy-MM-dd");//字符串转date类型
            int i = DateUtil.dayOfWeek(date);//获取当前周的第几天  返回的是2表示周一   返回一1表示周日
            if (i == 1) {
                date = DateUtil.offsetDay(date, 1);
            } else {
                date = DateUtil.offsetDay(date, -1);//offsetDay 对当前事件进行+，- 1天
            }
        }

        //这一周的开始时间和结束时间
        DateTime beginDate = DateUtil.beginOfWeek(date);
        DateTime endDate = DateUtil.endOfWeek(date);
        schedulingVo.setBeginDate(DateUtil.format(beginDate, "yyy-MM-dd"));
        schedulingVo.setEndDate(DateUtil.format(endDate, "yyy-MM-dd"));
//        根据条件查询排班表
        List<Scheduling> schedulings = queryByCondition(schedulingVo);

        List<SchedulingDto> schedulingDtos = new ArrayList<>();

//根据用户进行遍历
        for (User user : users) {
//            现在是没有排班的
            SchedulingDto schedulingDto1 = new SchedulingDto(user.getUserId(), user.getDeptId(), "1", initMap(beginDate));
            SchedulingDto schedulingDto2 = new SchedulingDto(user.getUserId(), user.getDeptId(), "2", initMap(beginDate));
            SchedulingDto schedulingDto3 = new SchedulingDto(user.getUserId(), user.getDeptId(), "3", initMap(beginDate));

            //一个用户都有这三条数据
            schedulingDtos.add(schedulingDto1);
            schedulingDtos.add(schedulingDto2);
            schedulingDtos.add(schedulingDto3);
            for (Scheduling scheduling : schedulings) {


//                Long userId = Long.valueOf(scheduling.getUserId());     //拍板人的id
                Long userId = scheduling.getUserId();
                String schedulingDay = scheduling.getSchedulingDay();   //排班的日期
                String subsectionType = scheduling.getSubsectionType();
                if (user.getUserId().equals(userId)) {
                    switch (subsectionType) {
                        case "1":                                        //上午排班
                            Map<String, String> record1 = schedulingDto1.getRecord();
                            record1.put(schedulingDay, scheduling.getSchedulingType());
                            break;
                        case "2":                                       //中午排班
                            Map<String, String> record2 = schedulingDto2.getRecord();
                            record2.put(schedulingDay, scheduling.getSchedulingType());
                            break;
                        case "3":                                         //晚上排班
                            Map<String, String> record3 = schedulingDto3.getRecord();
                            record3.put(schedulingDay, scheduling.getSchedulingType());
                            break;
                    }
                }

            }
//            拿到所有的一个排班内容
            schedulingDto1.setSchedulingType(schedulingDto1.getRecord().values());
            schedulingDto2.setSchedulingType(schedulingDto2.getRecord().values());
            schedulingDto3.setSchedulingType(schedulingDto3.getRecord().values());
        }
// 封装表数据
        Map<String, Object> result = new HashMap<>();
        result.put("tableData", schedulingDtos);
        result.put("beginDate", DateUtil.format(beginDate, "yyy-MM-dd"));
        result.put("endDate", DateUtil.format(endDate, "yyy-MM-dd"));

//        封装表头
        Object lable = initLable(beginDate);
        result.put("labelNames", lable);

        return new Result<>(2000, "查询成功", result);

    }

    //    封装标题
    private Object initLable(DateTime beginTime) {
        String[] labelName = new String[7];
        for (int i = 0; i < 7; i++) {
            DateTime d = DateUtil.offsetDay(beginTime, i);
            labelName[i] = DateUtil.format(d, "yyyy-MM-dd") + formatterWeek(i);

        }
        return labelName;
    }

    //    翻译周
    private String formatterWeek(int i) {
        switch (i) {
            case 0:
                return "(周一)";
            case 1:
                return "(周二)";
            case 2:
                return "(周三)";
            case 3:
                return "(周四)";
            case 4:
                return "(周五)";
            case 5:
                return "(周六)";
            default:
                return "(周日)";

        }
    }

    //    初始化当前用户这一周的排班信息
    private Map<String, String> initMap(DateTime beginDate) {
        Map<String, String> map = new TreeMap<>();//TreeMap有序
        for (int i = 0; i < 7; i++) {
            DateTime dateTime = DateUtil.offsetDay(beginDate, i);
            String key = DateUtil.format(dateTime, "yyyy-MM-dd");
            map.put(key, "");
        }
        return map;
    }


    //    根据条件查询排班信息
    public List<Scheduling> queryByCondition(SchedulingVo schedulingVo) {
        QueryWrapper<Scheduling> wrapper = new QueryWrapper<>();
        if (schedulingVo.getUserId() != null) {
            wrapper.eq("user_id", schedulingVo.getUserId());
        }
        if (schedulingVo.getDeptId() != null) {
            wrapper.eq("dept_id", schedulingVo.getDeptId());
        }
        if (StringUtils.hasText(schedulingVo.getBeginDate())) {
            wrapper.ge("scheduling_day", schedulingVo.getBeginDate());//ge  > 条件
        }
        if (StringUtils.hasText(schedulingVo.getEndDate())) {
            wrapper.le("scheduling_day", schedulingVo.getEndDate());//le >小于条件
        }
        return schedulingDao.selectList(wrapper);
    }


}



























